using System;
using CastleSample.Business.Interface;
using CastleSample.Core;
using CastleSample.Entity;

namespace CastleSample.Business.Remoting.Server
{
    public delegate void BizServiceCreatedEventHanlder(Type serviceInterface, IBizService serviceInstance);

    public class RemotingBizServiceFactory : MarshalByRefObject, IRemoteBizServiceFactory
    {
        public static event BizServiceCreatedEventHanlder ServiceCreated;

        private static T GetServiceInternal<T>(UserContext userContext) where T : IBizService
        {
            T service = GetServiceInternal<T>();
            service.CurrentUserContext = userContext;
            return service;
        }

        private static T GetServiceInternal<T>() where T : IBizService
        {
            LogService.InfoFormat(typeof (RemotingBizServiceFactory).FullName, "Request to create service proxy of {0}", typeof (T).FullName);
            T service = ServiceLocator.Get<T>(typeof (T).Name + "Proxy");
            if (ServiceCreated != null)
            {
                ServiceCreated(typeof (T), service);
            }

            if (service == null)
            {
                LogService.WarnFormat(typeof (RemotingBizServiceFactory).FullName, "Create service proxy of {0} returns null", typeof (T).FullName);
            }
            return service;
        }

        #region IRemotingBizServiceFactory Members

        public T GetService<T>(UserContext userContext) where T : IBizService
        {
            return GetServiceInternal<T>(userContext);
        }

        public T GetService<T>() where T : IBizService
        {
            return GetServiceInternal<T>();
        }

        #endregion
    }
}